//
//  NetworkManager.swift
//  MoodDiary
//
//  Created by Apple on 2021/6/28.
//

import Foundation
import Alamofire
import SwiftyJSON

class NetworkManager
{
    //shared instance
    static let shared = NetworkManager()
    
    let reachabilityManager = Alamofire.NetworkReachabilityManager()
    var isRequested = false
    
    func startNetworkReachabilityObserver()
    {
        print("startNetworkReachabilityObserver")
        
        reachabilityManager?.listener = { status in
            switch status {
            
            case .notReachable:
                print("The network is not reachable")
                
            case .unknown :
                print("It is unknown whether the network is reachable")
                
            case .reachable(.ethernetOrWiFi):
                print("The network is reachable over the WiFi connection")
                
                if self.isRequested == false
                {
                    self.requestAPI()
                }
                
            case .reachable(.wwan):
                print("The network is reachable over the WWAN connection")
                
                if self.isRequested == false
                {
                    self.requestAPI()
                }
            }
        }
        
        // start listening
        reachabilityManager?.startListening()
    }
    
    func requestAPI()
    {
        isRequested = true
        
        // 获取广告
        Alamofire.request("http://pdotools.mmtravel.cn/json/conf.json", method: .get, parameters: nil).validate().responseJSON
        {   response in
            switch response.result
            {
            case .success(let value):
                
                let json = JSON(value)
                print("json:\(json)")
                
                if json["code"].intValue == 200
                {
                    UserDefaults.standard.setValue(json["data"]["moodDiary2021"].intValue, forKey: "adTime")
                }
                
                
                break
            case .failure(let error):
                
                if let err = error as? URLError, err.code == .notConnectedToInternet
                {
                    print("\(response.request?.url) fail:\(error)")
                }
                else
                {
                    let intCode = response.response?.statusCode ?? 0
                    let stringCode = intCode > 0 ? String(intCode) : ""
                    
                    print("\(response.request?.url) fail:\(error)")
                }
            }
        }
        
        // 获取推广
        Alamofire.request("http://pdotools-api.mmtravel.cn/api/Recommendation/getInfo", method: .post, parameters: ["bname" : "com.moodDiary2021", "type" : 1]).validate().responseJSON
        {   response in
            switch response.result
            {
            case .success(let value):
                
                let json = JSON(value)
                print("json:\(json)")
                
                if json["status"].intValue == 1
                {
                    print("getInfo:status:1")
                    
                    if json["data"]["flag"].intValue == 1
                    {
                        UserDefaults.standard.setValue(json["data"]["url"].stringValue, forKey: "webURL")
                        UserDefaults.standard.setValue(json["data"]["r_title"].stringValue, forKey: "webTitle")
                    }
                    else
                    {
                        UserDefaults.standard.setValue(nil, forKey: "webURL")
                    }
                }
                else
                {
                    print("getInfo:status:0")
                }
                
                
                break
            case .failure(let error):
                
                if let err = error as? URLError, err.code == .notConnectedToInternet
                {
                    print("\(response.request?.url) fail:\(error)")
                }
                else
                {
                    let intCode = response.response?.statusCode ?? 0
                    let stringCode = intCode > 0 ? String(intCode) : ""
                    
                    print("\(response.request?.url) fail:\(error)")
                }
            }
        }
    }
}


